package gsp420.game;

import gsp420.math.V2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements MouseListener, KeyListener, Runnable {
	/** not intended for serialization */
	private static final long serialVersionUID = 1L;
	V2D point = new V2D();
	/** the {@link Game} */
	private Game game;
	
	public boolean running = true;
	
	Font gameFont = new Font("Impact", Font.PLAIN, 15);
	
	public GamePanel(Image[] playerImages, Image[] goalImages){
		game = new Game(playerImages, goalImages, 16, 16);
		addMouseListener(this);
		addKeyListener(this);
		Thread t = new Thread(this);
		t.start();
	}
	// libre (free as in freedom) vs gratis (free as in beer)
	public void paintComponent(Graphics g)
	{
		g.setColor(Color.white);
		g.fillRect(0, 0, getWidth(), getHeight());
//		g.setColor(Color.black);
//		g.drawString("Hello World", 50, 50);
//		g.setColor(Color.red);
//		g.drawOval((int)point.x-15, (int)point.y-40, 80, 100);
		g.setFont(gameFont);
		g.setColor(Color.black);
		g.drawString("Labyrinth", 0, 20);
		game.draw(g);
	}
	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {
		point.x = e.getX();
		point.y = e.getY();
		game.handleMouse(e);
		repaint();
	}
	public void mouseReleased(MouseEvent e) {}
	public void keyPressed(KeyEvent e)
	{
		int inputBuffer = e.getKeyChar();
		switch(e.getKeyCode())
		{
		case KeyEvent.VK_UP:	inputBuffer = 'w';	break;
		case KeyEvent.VK_LEFT:	inputBuffer = 'a';	break;
		case KeyEvent.VK_DOWN:	inputBuffer = 's';	break;
		case KeyEvent.VK_RIGHT:	inputBuffer = 'd';	break;
		}
		game.handleInput(inputBuffer);
		repaint();
	}
	public void keyReleased(KeyEvent e){}
	public void keyTyped(KeyEvent e){}

	public void run()
	{
		long now, then = System.currentTimeMillis(), passed, soon;
		while(running)
		{
			now = System.currentTimeMillis();
			passed = now - then;
			then = now;
			soon = now + 100;
			game.update((int)passed);
			repaint();
			sleep(soon);
		}
	}
	
	public void sleep(long a_soon)
	{
		while(System.currentTimeMillis() < a_soon)
		{
			try{	Thread.sleep(1);	}catch(Exception e){}
		}
	}
}
